package haiyan.common.security;

import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import java.security.NoSuchAlgorithmException;
import javax.crypto.SecretKey;
import java.io.*;

/**
 * @author zhouxw
 * 
 */
public class CreateKey {

	/**
	 * 
	 */
	String filename = "";

	/**
	 * 
	 */
	CreateKey() {
	}

	/**
	 * @param filename
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 */
	void createKeyFile(String filename) throws IOException,
			NoSuchAlgorithmException {
		this.filename = filename;
		if (filename == null || filename.equals("")) {
			throw new NullPointerException("...");
		}
		createKey();
	}

	/**
	 * @return String
	 */
	String getKeyFilePath() {
		return filename;
	}

	/**
	 * @throws IOException
	 * @return byte[]
	 */
	byte[] getKeyByte() throws IOException {
		byte[] bytes = DesUtil.readFile(filename);
		return bytes;
	}

	/**
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	private void createKey() throws NoSuchAlgorithmException, IOException {
		SecureRandom secureRandom = new SecureRandom();
		//
		KeyGenerator kg = KeyGenerator.getInstance(DesUtil.getValue("algorithm"));
		kg.init(secureRandom);
		//
		SecretKey key = kg.generateKey();
		//
		DesUtil.writeFile(key.getEncoded(), filename);
	}

}
